package com.zx.mes.rocketmq.hyl.transaction;

import com.zx.mes.rocketmq.hyl.constant.Const;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * rocket mq transaction
 * 与平时普通的consumer没什么区别
 *
 * @author 华云龙
 * @date 2018-12-3
 */
@Log4j2
public class Consumer {

    public static void main(String[] args) throws MQClientException {

///       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Const.TRANSACTION_ROCKET_MQ_GROUP_NAME);

        consumer.setConsumeThreadMin(10);

        consumer.setConsumeThreadMax(20);

        consumer.setNamesrvAddr(Const.NAMESRV_ADDR_SINGLE);

        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);

        consumer.subscribe(Const.TRANSACTION_ROCKET_MQ_TOPIC, Const.SUB_EXPRESSION);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                MessageExt messageExt = msgs.get(0);

                try {
///                System.out.println(sdf.format(new Date())+",consumer: "+messageExt);
                    log.info(messageExt);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
        System.out.println("transaction consumer start ...");
    }
}
